<template>
  <a-upload
    v-model:file-list="fileList"
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="false"
    :before-upload="beforeUpload"
    :custom-request="customRequest"
  >
    <img v-if="fileList.length" :src="fileList[0].url as unknown as string" alt="avatar" class="image" />
    <div v-else>
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined v-else></plus-outlined>
      <div class="ant-upload-text">Upload</div>
    </div>
  </a-upload>
</template>
<script lang="ts" setup>
import { computed, ref } from "vue"
import { PlusOutlined } from "@ant-design/icons-vue"
import { message, notification } from "ant-design-vue"
import { uploadFileBySDK } from "@/db"

interface UploadProps {
  value: any[]
}
const props = defineProps<UploadProps>()
const $emit = defineEmits(["update:value"])
const loading = ref<boolean>(false)

let fileList = computed({
  get() {
    return props.value ? [{ url: props.value }] : []
  },
  set(newVal) {
    $emit("update:value", newVal)
  }
})

const beforeUpload = (file: any) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png"
  if (!isJpgOrPng) {
    message.error("图片格式要求为 JPG 或PNG!")
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error("图片大小不能超过 2MB!")
  }
  return isJpgOrPng && isLt2M
}
const customRequest = async (file: any) => {
  loading.value = true
  let data: any = await uploadFileBySDK(file.file, "用户头像")
  loading.value = false
  if (data.code == 0) {
    $emit("update:value", data.data.path)
  } else {
    notification.error({
      message: data.message
    })
  }
  return true
}
</script>
<style lang="scss" scoped>
.image {
  width: 100px;
  height: 100px;
}
:deep(.ant-upload-select-picture-card i) {
  font-size: 32px;
  color: #999;
}

:deep(.ant-upload-select-picture-card .ant-upload-text) {
  margin-top: 8px;
  color: #666;
}
</style>
